﻿using System.Collections;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

namespace RSAID
{
    public partial class UserDefinedFunctions
    {
        [SqlFunction(FillRowMethodName = "ValidateRSAIDFillRow", 
                     TableDefinition   = "IsValid bit, IsCitizen bit, Gender nchar(1), DateOfBirth DateTime")]
        public static IEnumerator ValidateRSAID(SqlString IdNumber)
        {
            yield return IdNumber.IsNull ? null : new ValidatedRSAID(IdNumber.Value);
        }

        public static void ValidateRSAIDFillRow(object obj, 
                                                out SqlBoolean IsValid, 
                                                out SqlBoolean IsCitizen, 
                                                out SqlString Gender, 
                                                out SqlDateTime DateOfBirth)
        {
            var id = obj as ValidatedRSAID;
            if (id == null)
            {
                IsValid = false;
                IsCitizen = SqlBoolean.Null;
                Gender = SqlString.Null;
                DateOfBirth = SqlDateTime.Null;
            }
            else
            {
                IsValid = id.IsValid;
                IsCitizen = id.IsCitizen.HasValue ? id.IsCitizen.Value : SqlBoolean.Null;
                DateOfBirth = id.DateOfBirth.HasValue ? id.DateOfBirth.Value : SqlDateTime.Null;
                Gender = id.Gender.HasValue
                             ? (id.Gender.Value == RSAID.Gender.Female ? "F" : "M")
                             : SqlString.Null;
            }
        }
    };
}
